Ext.define('FEditForm', {
    extend: 'FForm',
    alias: 'widget.feditform',
    
    // Campos do form.
    formFields: null,
    
    /**
     * Ação do form: 'insert', 'update', 'view'. Default 'insert'.
     */
    formAction: 'insert',
    
    /**
     * Identificador do registro a ser editado.
     */
    dataId: 0,
    
    /**
     * Nome do campo identificador. Default 'id'.
     */
    idxName: 'id',
    
    /**
     * Se deve ser gerado um campo do identificador ao editar. Default true.
     */
    genField: true,
    
    /**
     * Se o campo identificador deve ser visível ou não. Default false.
     */
    hideIndexField: false,        
    
    onShow: function()
    {
        if ( this.formAction == 'update' )
        {
            this.formPanel.getForm().load(
            {
                url: this.handlerUrl,
                params: {
                    manager: this.className,
                    action: 'get',
                    table: this.table,
                    idxName: this.idxName,
                    dataId: this.dataId
                },
                scope: this,
                success: function(form, request)
                {
                    this.obj = Ext.JSON.decode(request.response.responseText);
                },
                failure: function(form, request)
                {
                    this.obj = Ext.JSON.decode(request.response.responseText);
                    Ext.create('FMessageError', {
                        msg: this.obj.msg ? this.obj.msg : 'Erro ao processar sua requisição.'
                    }).show();
                }
            });
        }
        
        this.callParent();
    },
    
    // PRIVATE
    editFields: null,
    initComponent: function()
    {        
        this.editFields = this.formFields;
        
        /*if ( this.formAction == 'update' && this.genField )
        {
            var fieldSet = new Ext.form.FieldSet(
            {
                baseCls: 'x-fieldset-noborder',
                items: [{
                    xtype: 'ftextfield',
                    fieldWidth: 80,
                    name: this.idxName,
                    // TODO: Melhorar o label
                    label: this.idxName,
                    hidden: this.hideIndexField,
                    readOnly: true,
                    allowBlank: false
                }].concat(this.editFields)
            });
        }
        else*/
        {
            var fieldSet = new Ext.form.FieldSet(
            {
                baseCls: 'x-fieldset-noborder',                
                items: this.editFields
            });
        }
        
        this.formPanel = new Ext.form.FormPanel(
        {
            cls: 'form',
            baseCls: 'x-fieldset-noborder',
            layout: 'form',
            padding: '10 10 10 20',
            width: '100%',
            items: fieldSet
        });
        
        this.tbar = [{
            text: 'Opções',
            iconCls: 'foptions-icon',
            menu: [
            {
                text: 'Salvar',
                iconCls: 'fbuttonsave-icon',
                scope: this,
                handler: this._onBtnSaveClick
            },
            {
                text: 'Cancelar',
                iconCls: 'fbuttoncancel-icon',
                scope: this,
                handler: this._onBtnCancelClick
            }
            ]
        }];
    
        this.formFields = [{
            xtype: 'panel',
            width: '100%',
            flex: 1,
            items: this.formPanel
        }];
    
        this.buttons = [{
            xtype: 'fbuttonsave',
            text: 'Salvar',
            iconCls: 'fbuttonsave-icon',
            width: 150,
            scope: this,
            handler: this._onBtnSaveClick
        },
        {
            xtype: 'fbuttoncancel',
            text: 'Cancelar',
            iconCls: 'fbuttoncancel-icon',
            width: 150,
            scope: this,
            handler: this._onBtnCancelClick
        }];
        
        if ( this.title == null )
        {
            if ( this.formAction == 'insert')
            {
                this.title = 'Inserindo registro...';
            }
            else
            {
                this.title = 'Editando registro...';
            }
        }
        
        this.callParent();
    },
    _onBtnSaveClick: function()
    {
        var form = this.formPanel.getForm();

        if ( !form.isValid() )
        {
            Ext.create('FMessageAlert', {
                msg: 'Preencha corretamente os campos!'
            }).show();
        }
        else
        {           
            this.el.mask('Salvando informações...');

            form.submit({
                url: this.handlerUrl,
                params: {
                    manager: this.className,
                    action: this.formAction,
                    table: this.table,
                    idxName: this.idxName,
                    dataId: this.dataId
                },
                scope: this,
                success: function(form, action)
                {
                    this.obj = Ext.JSON.decode(action.response.responseText);

                    var detail;
                    for (var count = 0; count < this.editFields.length; count++)
                    {
                        if ( this.editFields[count].xtype == 'fdetail' )
                        {
                            detail = this.editFields[count];

                            if ( this.formAction == 'insert' )
                            {
                                this.dataId = this.obj.id;
                            }
                            
                            Ext.Ajax.request({
                                async: false,
                                url: detail.handlerUrl,
                                params: {
                                    manager: detail.masterTable,
                                    formAction: detail.formAction,
                                    detailName: detail.name,
                                    detailTable: detail.detailTable,
                                    detailIndexName: detail.detailIndexName,
                                    masterIndexName: detail.masterIndexName,
                                    masterIndex: this.dataId,
                                    action: 'save'
                                }
                            });
                        }
                    }

                    this.el.unmask();
                    this.formPanel.getForm().reset();
                    
                    Ext.create('FMessageSuccess', {
                        msg: this.obj.msg
                    }).show();

                    this.doClose();
                },
                failure: function(form, action)
                {
                    this.el.unmask();
                   
                    this.obj = Ext.JSON.decode(action.response.responseText);
                    Ext.create('FMessageError', {
                        msg: this.obj.msg
                    }).show();
                }
            });
        }
    },
    _onBtnCancelClick: function()
    {
        this.getCloseAction();
    },
    close: function()
    {
        this.getCloseAction();
    },
    getCloseAction: function()
    {
        Ext.Msg.confirm('Confirmação', '<b>Deseja cancelar a edição deste registro?</b>', function(btn)
        {
            if( btn == 'yes' )
            {
                var detail;
                for (var count = 0; count < this.editFields.length; count++)
                {
                    if ( this.editFields[count].xtype == 'fdetail' )
                    {
                        detail = this.editFields[count];

                        Ext.Ajax.request({
                            async: false,
                            url: detail.handlerUrl,
                            params: {
                                manager: detail.masterTable,
                                masterIndex: this.dataId,
                                action: 'clear'
                            }
                        });
                    }
                }
                
                
                this.doClose();
            }
        }, this);
    }
});
